$(function() {
    showCondition(true, 1, 1, 1, []);
    var totalCaseCnt;
    var drgCode = '';
    var isFirst = true;
    var barColor = ["#50a1d4", "#f07043", "#7bd9a5", "#d0648a", "#f58db2", "#f2b3c9"];

    //全院总体指标
    var totalQuota = [
        ['InCaseCnt', '病例数'],
        ['FeeEff', '费用消耗指数'],
        ['AvgFee', '次均费用'],
        ['AvgDays', '平均住院日'],
        ['AvgDrugFee', '次均药品费用(元)'],
        ['DrugRatio', '药品费用占比(%)'],
        ['AvgMateFee', '次均耗材费用(元)'],
        ['MaterialRatio', '耗材费用占比(%)'],
        ['MedFee', '医疗费'],
        ['NursFee', '护理费'],
        ['ManageFee', '管理费'],
        ['TechFee', '医技费'],
        ['DrugMaterFee', '药品耗材费']
    ];

    //获取指标值
    function getQuotaValue(quotaCode, monitorType, callback, drgCode) {
        var param = drgUI.setAjaxData(tabId);
        param.monitorType = monitorType;
        if (drgCode) {
            param.pardrgCode = drgCode;
        }
        param.quotaCode = quotaCode;

        $.post(contextPath + "/DrgsIndexCal/indexCal.dhc", param).done(function (data) {
            if (data.success) {
                if (data.data.length > 0) {
                    data = data.data;
                    callback(data);
                }
            }
        });
    }

    //获取整体情况
    getQuotaValue('TotalFee,TotalCaseCnt', 'dep', function (result) {
        totalCaseCnt = result[0].TotalCaseCnt;
    });

    //查询病组次均费用、费用构成及其对比情况表
    function queryDRGQuota() {
        var quotaCode = totalQuota.map(function(v) {return  v[0]}).join(',');
        quotaCode += ',TotalCaseCnt,FeeEff,ExcessCnt_F';
        var columns = [
            {
                "className": 'details-control',
                "orderable": false,
                "data": null,
                "defaultContent": '',
                width: 20
            },
            {
                "data": "drg", "title": 'DRG',
                "render": function (obj, type, full) {
                    return '<span data-toggle="tooltip" data-placement="right" title="' + full.DDESC + '">' + full.CCODE + '</span>';
                }
            }
        ];

        //根据页面选择的指标，动态拼接表头
        for (var i = 0; i < totalQuota.length; i++) {
            var q = totalQuota[i];
            //for (var q of totalQuota) {
            (function (q) {
                q[0] = q[0].toUpperCase();
                columns.push({
                    "data": q[0], "title": q[1],
                    "render": function (obj, type, full) {
                        //return formatNumber(full.TotalCaseCnt*100/totalCaseCnt,2);
                        if (full[q[0]] > full[q[0] + 'CC']) {
                            return '<span class="text-danger" title="超标">' + full[q[0]] + '</span>';
                        } else {
                            return '<span>' + full[q[0]] + '</span>';

                        }
                    }
                });
            }(q));
        }
        var paramsDataTables = {
            searching: true,
            lengthChange: true,
            ordering: true,
            info: false,
            // scrollX:true,
            // scrollY:'285px',
            orderCellsTop: true,
            order: [[3, 'desc']]
        };

        var param = drgUI.setAjaxData(tabId);
        //次均费用、费用构成及其对比情况表数据获取
        $.post(contextPath + "/feeAnalysisDep/getDrgCompareData.dhc", param).done(function (data) {
            if (data.success) {
                if (data.data.length > 0) {
                    var data = data.data;
                    renderFeeStrucTable(data);
                }
            }
        });

        //year: 同比
        //month: 环比
        //hosp: 院内均值
        //getQuotaValue(quotaCode, 'drgs', function (data) {
        function renderFeeStrucTable(data) {
            drgCode = data[0].CCODE;
            var table = $("#drgFeeTable").dataTableBasic(columns, data, paramsDataTables);
            $('[data-toggle="tooltip"]').tooltip();

            //展开某病组的费用信息
            $('#drgFeeTable tbody').on('click', 'td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                } else {
                    drgCode = row.data().CCODE;
                    row.child('<div class="col-sm-6" id="feeCompChart' + drgCode + '" style="height:280px;"></div>' +
                        '<div class="col-sm-6" id="feeStackChart' + drgCode + '" style="height:280px;"></div>' +
                        '<div class="col-sm-12"><table class="table" id="feeCompTable' + drgCode + '" style="width: 100%;"><caption><h5>' + drgCode + '-' + row.data().DDESC + '病组次均费用、费用构成及其对比情况表</h5></caption></table></div>').show();
                    tr.addClass('shown');

                    //请求数据
                    var quota = [
                        ['MedFee', '医疗费'],
                        ['NursFee', '护理费'],
                        ['ManageFee', '管理费'],
                        ['TechFee', '医技费'],
                        ['DrugMaterFee', '药品耗材费']
                    ];
                    var otherFeeQuota = [
                        ['AvgFee', '次均费用'],
                        ['AvgDays', '平均住院日'],
                        ['AvgDrugFee', '次均药品费用'],
                        ['DrugRatio', '药品费用占比'],
                        ['AvgMateFee', '次均耗材费用'],
                        ['MaterialRatio', '耗材费用占比']
                    ];

                    //病组展开的 次均费用、费用构成及其对比情况表
                    var paramA = drgUI.setAjaxData(tabId);
                    paramA.pardrgCode = drgCode;
                    $.post(contextPath + "/feeAnalysisDep/getDrgFeeCompareTable.dhc", paramA).done(function (data) {
                        if (data.success) {
                            if (data.data.length > 0) {
                                var data = data.data;
                                renderDRGDetail(data)
                            }
                        }
                    });

                    //getQuotaValueAllCompare(quota.map(v{return v[0]).join(',')+','+otherFeeQuota.map(v{return v[0]).join(',')+','+'TotalFee', 'drgs', function (data) {
                    function renderDRGDetail(data) {
                        var seriesData = [{
                            name: '总费用',
                            type: 'bar',
                            //data: data.map(v{return v.MedFeecc+v.NursFeecc+v.ManageFeecc+v.TechFeecc+(v.DrugMaterFeecc||0))
                            data: data.map(function(v) {return  v.MEDFEE + v.NURSFEE + v.MANAGEFEE + v.TECHFEE + (v.DRUGMATERFEE || 0)})
                        }];
                        for (var i = 0; i < quota.length; i++) {
                            var q = quota[i];
                            //for (var q of quota) {
                            (function (q) {
                                q[0] = q[0].toUpperCase();
                                seriesData.push({
                                    name: q[1],
                                    type: 'bar',
                                    stack: '五大类费用',
                                    data: data.map(function(v) {return  v[q[0]]})
                                });
                            }(q));
                        }
                        drawBarChart('feeCompChart' + drgCode, drgCode + '病组次均费用对比图', quota.map(function(v){return v[1]}), data.map(function(v) {return  v.DDESC}), seriesData);


                        var seriesDataStack = [];

                        for (var i = 0; i < quota.length; i++) {
                            var q1 = quota[i];
                            //for (var q1 of quota) {
                            (function (q) {
                                q[0] = q[0].toUpperCase();
                                seriesDataStack.push({
                                    name: q[1],
                                    type: 'bar',
                                    stack: '五大类费用',
                                    data: data.map(function(v) {return  v[q[0]]})
                                });
                            }(q1));
                        }
                        drawBarChart('feeStackChart' + drgCode, drgCode + '病组费用构成及其对比图', quota.map(function(v) {return  v[1]}), data.map(function(v) {return  v.DDESC}), seriesDataStack);


                        //表格
                        var columns = [
                            {"data": "DDESC", "title": '比较对象'}
                        ];
                        //拼接表头
                        for (var i = 0; i < otherFeeQuota.concat(quota).length; i++) {
                            var q = otherFeeQuota.concat(quota)[i];
                            //for (var q of otherFeeQuota.concat(quota)) {
                            (function (q) {
                                q[0] = q[0].toUpperCase();
                                columns.push({"data": q[0], "title": q[1]});
                            }(q));
                        }
                        $('#feeCompTable' + row.data().CCODE).dataTableBasic(columns, data, {dom: '<"top">t<"bottom"><"clear">'});

                    }
                }
            });

            //按入组病例数倒序
            data.sort(function (a, b) {
                return b.INCASECNT - a.INCASECNT;
            });

            //截取前十
            var top10Array = data.filter(function(v) {return  v.EXCESSCNT_F > 0}).filter(function(v, i) {return  i < 10}).map(function (v) {
                return {
                    value: v.EXCESSCNT_F,
                    name: v.CCODE + '-' + v.DDESC
                }
            });
            //除前十外的归为其他
            var otherArray = data.filter(function(v) {return  v.EXCESSCNT_F > 0}).filter(function(v, i) {return  i > 10}).map(function (v) {
                return Number(v.EXCESSCNT_F);
            })
            if (otherArray.length > 0) {
                var otherArrayTotal = otherArray.reduce(function (s, v) {
                    return s + v;//求和
                });
                top10Array.push({name: '其他', value: otherArrayTotal});
            }

            var casePieChartOption = {
                title: {
                    text: 'DRG病组内超标病例数分布图',
                    textStyle: {
                        fontSize: 14
                    }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: "{b}<br/> {c} ({d}%)"
                },
                color: barColor,
                series: [{
                    name: '超标病例数',
                    selectedMode: 'single',
                    radius: [0, '50%'],
                    label: {
                        normal: {
                            formatter: function (param) {
                                return param.name.substr(0, 4) + ' : ' + param.value + '例 (' + param.percent.toFixed(1) + '%)';
                            },
                            backgroundColor: '#eee',
                            borderColor: '#aaa',
                            borderWidth: 1,
                            fontSize: 16,
                            lineHeight: 33,
                            padding: [4, 6],
                            borderRadius: 2
                        }
                    },
                    data: top10Array,
                    type: 'pie'
                }]
            };
            var casePieChart = echarts.init(document.getElementById('casePieChart'));
            casePieChart.setOption(casePieChartOption);
        }

    }

    queryDRGQuota();

    function drawBarChart(id, title, legend, category, seriesData) {
        var option = {
            title: {
                text: title,
                textStyle: {
                    fontSize: 15
                }
            },
            grid: {
                left: 170
            },
            tooltip: {
                trigger: 'axis',
                position: [0, 20],
                axisPointer: {            // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow'        // 默认为直线，可选为：'line' | 'shadow'
                }
            },
            legend: {
                top: 20,
                data: legend
            },
            yAxis: [
                {
                    type: 'category',
                    data: category
                }
            ],
            xAxis: [
                {
                    type: 'value'
                }
            ],
            series: seriesData
        };

        var chart = echarts.init(document.getElementById(id));
        chart.setOption(option);
    }
});

